﻿using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 基于WPF的电缆采样数据分析系统.Models.Dbs.DbService;
using 基于WPF的电缆采样数据分析系统.MsgEvents;
using 基于WPF的电缆采样数据分析系统.MsgEvents.Login;
using 基于WPF的电缆采样数据分析系统.Tools.LangugeTool;
using 基于WPF的电缆采样数据分析系统.Models.Enums;
using System.IO;
using 基于WPF的电缆采样数据分析系统.Tools.RemenberUserTools;
using 基于WPF的电缆采样数据分析系统.Models.Dbs;


namespace 基于WPF的电缆采样数据分析系统.ViewModels.Users
{
     public class LoginUCViewModel : BindableBase, IDialogAware
    {

        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get; set; } = LangugeConvertor.GetValue("CableSamplingDataAnalysisSystemBasedOnWPF");

        /// <summary>
        /// 请求关闭(关闭对话框时触发)
        /// </summary>
        public event Action<IDialogResult> RequestClose;


        /// <summary>
        /// 事件聚合器（用于发布订阅）
        /// </summary>
        private readonly IEventAggregator Aggregator;

        #region 登录

        /// <summary>
        /// 登录命令
        /// </summary>
        public DelegateCommand LoginCmm { get; set; }

        /// <summary>
        /// 登录方法
        /// </summary>
        private void Login()
        {
            /// 账号或密码不能为空
            if (string.IsNullOrEmpty(LoginAccount) || string.IsNullOrEmpty(LoginPassword))
            {
                Aggregator.GetEvent<MsgLoginInfo>().Publish("账号或密码不能为空");
                return;
            }

            // 登录
            RetResult retResult = UserService.Instance.LoginByAccountAndPassword(LoginAccount, LoginPassword);

            if (retResult == RetResult.Fail)
            {
                User user = UserService.Instance.GetUserByAccountAndPassword(LoginAccount, LoginPassword);

                // 用户不存在
                if (user == null)
                {
                    Aggregator.GetEvent<MsgLoginInfo>().Publish("账号或密码错误");
                    return;
                }

                // 用户禁用
                if (user.IsEnable == 0)
                {
                    Aggregator.GetEvent<MsgLoginInfo>().Publish("该用户已被禁用");
                    return;
                }

                return;
            }

            // 登录成功
            Aggregator.GetEvent<MsgLoginInfo>().Publish("登录成功");
            GlobalVariableEdit.CurrentUserInfo = UserService.Instance.GetUserByAccountAndPassword(LoginAccount, LoginPassword);
            UserUsedRecordService.Instance.AddUserUsedRecord(GlobalVariableEdit.CurrentUserInfo.Uid);

            if (RememberPassword)
            {
                WriteUserInfo(LoginAccount, LoginPassword);
            }
            else
            {
                DeleteUserInfo();
            }

            // 设置用户别名
            Aggregator.GetEvent<MsgLoginUserName>().Publish(GlobalVariableEdit.CurrentUserInfo.Alias);

            RequestClose(new DialogResult(ButtonResult.OK));
        }

        #endregion

        /// <summary>
        /// 显示注册信息命令
        /// </summary>
        public DelegateCommand ShowRegInfoCmm { get; set; }

        /// <summary>
        /// 显示登录信息命令
        /// </summary>
        public DelegateCommand ShowLoginInfoCmm { get; set; }

        #region 注册

        /// <summary>
        /// 注册命令
        /// </summary>
        public DelegateCommand RegisterCmm { get; set; }

        /// <summary>
        /// 注册方法
        /// </summary>
        private void Regsiter()
        {
            if (string.IsNullOrEmpty(RegisterAlias))
            {
                Aggregator.GetEvent<MsgLoginInfo>().Publish("姓名不能为空");
                return;
            }

            if (string.IsNullOrEmpty(RegisterAccount))
            {
                Aggregator.GetEvent<MsgLoginInfo>().Publish("账号不能为空");
                return;
            }

            if (string.IsNullOrEmpty(RegisterPassword))
            {
                Aggregator.GetEvent<MsgLoginInfo>().Publish("输入密码不能为空");
                return;
            }

            if (string.IsNullOrEmpty(RegisterConfirmPassword))
            {
                Aggregator.GetEvent<MsgLoginInfo>().Publish("重新输入密码不能为空");
                return;
            }

            if (!string.Equals(RegisterPassword, RegisterConfirmPassword))
            {
                Aggregator.GetEvent<MsgLoginInfo>().Publish("输入密码和重新输入密码不一致");
                return;
            }

            if (string.IsNullOrEmpty(InvitationCode))
            {
                Aggregator.GetEvent<MsgLoginInfo>().Publish("邀请码不能为空");
                return;
            }


            if (InvitationCodeRecordService.Instance.IsInvitationCodeExist(InvitationCode) == 0 ||
                InvitationCodeRecordService.Instance.GetInvitationCodeRecord(InvitationCode).IsUsed == 1)
            {
                Aggregator.GetEvent<MsgLoginInfo>().Publish("邀请码不存在或已被使用");
                return;
            }

            if (UserService.Instance.GetUserByAccount(RegisterAccount) == 1)
            {
                Aggregator.GetEvent<MsgLoginInfo>().Publish("账号已存在");
                return;
            }

            // 注册
            RetResult retResult = UserService.Instance.RegisterUser(RegisterAlias, RegisterAccount, RegisterPassword);

            // 注册成功
            if (retResult == RetResult.Success)
            {
                // 获取刚刚注册成功的用户信息
                User user = UserService.Instance.GetUserByAccountAndPassword(RegisterAccount, RegisterPassword);

                RetResult retResult1 = InvitationCodeRecordService.Instance.UpdateInvitationCodeRecordStatusAndRegisterId(InvitationCode, user.Uid);

                // 成功修改邀请码信息
                if (retResult1 == RetResult.Success)
                {

                    Aggregator.GetEvent<MsgLoginInfo>().Publish("注册成功");


                    // 赋值登录信息
                    LoginAccount = RegisterAccount;
                    LoginPassword = RegisterPassword;

                    // 清空注册信息
                    RegisterAlias = string.Empty;
                    RegisterAccount = string.Empty;
                    RegisterPassword = string.Empty;
                    RegisterConfirmPassword = string.Empty;
                    InvitationCode = string.Empty;

                    // 返回登录页面
                    ShowLoginInfo();
                    return;
                }
            }

            // 注册失败
            Aggregator.GetEvent<MsgLoginInfo>().Publish("注册失败");

        }

        #endregion

        /// <summary>
        /// 初始化
        /// </summary>
        public LoginUCViewModel(IEventAggregator _Aggregator)
        {
            // 登录命令
            LoginCmm = new DelegateCommand(Login);
            // 显示注册页面
            ShowRegInfoCmm = new DelegateCommand(ShowRegInfo);
            // 显示登录页面
            ShowLoginInfoCmm = new DelegateCommand(ShowLoginInfo);
            // 注册命令
            RegisterCmm = new DelegateCommand(Regsiter);

            // 发布订阅
            Aggregator = _Aggregator;

            // 默认账号密码(开发者)
            //LoginAccount = "wangzhi";
            //LoginPassword = "123456";

            // 获取当前项目的根目录
            string projectRoot = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
            string remenberPath = projectRoot.Substring(0, projectRoot.Length - 3) + "temp\\remenber.list";

            if (RemenberUserInfoTool.IsExist(remenberPath))
            {
                // 读取用户信息
                ReadUserInfo();
            }

        }



        /// <summary>
        /// 显示注册信息
        /// </summary>
        private void ShowRegInfo()
        {
            SelectedIndex = 1;
        }

        /// <summary>
        /// 显示登录信息
        /// </summary>
        private void ShowLoginInfo()
        {
            SelectedIndex = 0;
        }




        /// <summary>
        /// 是否能够关闭对话框
        /// </summary>
        /// <returns></returns>
        public bool CanCloseDialog()
        {
            return true;
        }

        /// <summary>
        /// 关闭
        /// </summary>
        public void OnDialogClosed()
        {

        }

        /// <summary>
        /// 打开
        /// </summary>
        /// <param name="parameters"></param>
        public void OnDialogOpened(IDialogParameters parameters)
        {

        }


        #region 显示内容的

        /// <summary>
        /// 显示内容的索引
        /// </summary>
        private int _SelectedIndex;

        /// <summary>
        /// 显示内容的索引
        /// </summary>
        public int SelectedIndex
        {
            get { return _SelectedIndex; }
            set
            {
                _SelectedIndex = value;
                RaisePropertyChanged();
            }
        }

        #endregion


        #region 登录账号
        /// <summary>
        /// 登录账号
        /// </summary>
        private string _LoginAccount;

        /// <summary>
        /// 登录密码
        /// </summary>
        public string LoginAccount
        {
            get { return _LoginAccount; }
            set
            {
                _LoginAccount = value.Trim();
                RaisePropertyChanged();
            }
        }

        #endregion


        #region 登录密码

        /// <summary>
        /// 登录密码
        /// </summary>
        private string _LoginPassword;

        /// <summary>
        /// 登录密码
        /// </summary>
        public string LoginPassword
        {
            get { return _LoginPassword; }
            set
            {
                _LoginPassword = value.Trim();
                RaisePropertyChanged();
            }
        }

        #endregion


        #region 注册信息

        /// <summary>
        /// 注册别名
        /// </summary>
        private string _RegisterAlias;

        /// <summary>
        /// 注册别名
        /// </summary>
        public string RegisterAlias
        {
            get { return _RegisterAlias; }
            set { 
                _RegisterAlias = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 注册账号
        /// </summary>
        private string _RegisterAccount;

        /// <summary>
        /// 注册账号
        /// </summary>
        public string RegisterAccount
        {
            get { return _RegisterAccount; }
            set { 
                _RegisterAccount = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 注册输入密码
        /// </summary>
        private string _RegisterPassword;

        /// <summary>
        /// 注册输入密码
        /// </summary>
        public string RegisterPassword
        {
            get { return _RegisterPassword; }
            set { 
                _RegisterPassword = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 注册重新输入密码
        /// </summary>
        private string _RegisterConfirmPassword;

        /// <summary>
        /// 注册重新输入密码
        /// </summary>
        public string RegisterConfirmPassword
        {
            get { return _RegisterConfirmPassword; }
            set { 
                _RegisterConfirmPassword = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 邀请码
        /// </summary>
        private string _InvitationCode;

        /// <summary>
        /// 邀请码
        /// </summary>
        public string InvitationCode
        {
            get { return _InvitationCode; }
            set { 
                _InvitationCode = value;
                RaisePropertyChanged();
            }
        }


        #endregion


        #region 记住密码

        /// <summary>
        /// 是否记住密码
        /// </summary>
        private bool _RememberPassword = true;

        /// <summary>
        /// 是否记住密码
        /// </summary>
        public bool RememberPassword
        {
            get { return _RememberPassword; }
            set { 
                _RememberPassword = value;
                RaisePropertyChanged();
            }
        }


        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        private void WriteUserInfo(string name, string password)
        {
            // 获取当前项目的根目录
            string projectRoot = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
            string remenberPath = projectRoot.Substring(0, projectRoot.Length - 3) + "temp\\remenber.list";

            User user = new User();
            user.Account = name;
            user.Password = password;

            RemenberUserInfoTool.WriteUserInfo(user, remenberPath);
        }

        /// <summary>
        /// 读取用户信息
        /// </summary>
        /// <returns></returns>
        public void ReadUserInfo()
        {
            // 获取当前项目的根目录
            string projectRoot = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
            string remenberPath = projectRoot.Substring(0, projectRoot.Length - 3) + "temp\\remenber.list";

            User user = RemenberUserInfoTool.ReadUserInfo(remenberPath);

            // 根据上次文件显示用户名和密码
            LoginAccount = user.Account;
            LoginPassword = user.Password;
        }

        /// <summary>
        /// 删除用户信息文件
        /// </summary>
        public void DeleteUserInfo()
        {
            // 获取当前项目的根目录
            string projectRoot = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
            string remenberPath = projectRoot.Substring(0, projectRoot.Length - 3) + "temp\\remenber.list";

            RemenberUserInfoTool.DeleteFileByPath(remenberPath);
        }

        #endregion
    }
}
